<?php

namespace App\Services\Idcard;

use YQ\YqCurl;

class IdcardCountryAuthApi
{
    public $appId     = ''; // 应用标识
    public $secretKey = ''; // 应用秘钥
    public $bizId     = ''; // 游戏备案识别码

    public function __construct($app_id, $app_secret, $biz_id)
    {
        $this->appId     = $app_id;
        $this->secretKey = $app_secret;
        $this->bizId     = $biz_id;
    }

    private function getHeaders($sign = null, $header_content_type = true)
    {
        $params = [
            'appId'        => $this->appId,
            'bizId'        => $this->bizId,
            'timestamps'   => intval(microtime(true) * 1000),
            'sign'         => $sign,
        ];
        if ($header_content_type == true) {
            $params['Content-Type'] = "application/json;charset=utf-8";
        }

        return $params;
    }

    private function buildHeaders($headers)
    {
        foreach (['Content-Type', 'appId', 'bizId', 'timestamps', 'sign'] as $val) {
            if (isset($headers[$val])) {
                $params[] = "{$val}:" . $headers[$val];
            }
        }

        return $params;
    }

    private function createBody($string)
    {
        return json_encode(['data' => $this->aesGcmEncrypt($string)]);
    }

    private function aesGcmEncrypt($string)
    {
        if (is_array($string)) {
            $string = json_encode($string);
        }

        $cipher  = strtolower('AES-128-GCM');
        $skey    = hex2bin($this->secretKey);
        $iv      = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher));
        $tag     = null;
        $content = openssl_encrypt($string, $cipher, $skey, OPENSSL_RAW_DATA, $iv, $tag);
        $str     = bin2hex($iv) . bin2hex($content) . bin2hex($tag);

        return base64_encode(hex2bin($str));
    }

    private function createSign($body, $header_content_type = true)
    {
        $data = $this->getHeaders(null, $header_content_type);
        if (is_array($body)) {
            $data += $body;
        }

        ksort($data);
        $source = [$this->secretKey];
        foreach ($data as $key => $value) {
            if ($key !== 'sign' && $key != 'Content-Type') {
                $source[] = "{$key}{$value}";
            }
        }
        if (!is_array($body)) {
            $source[] = $body;
        }

        $presign = implode('', $source);

        return hash('sha256', $presign);
    }

    public function check($idcard_name, $idcard)
    {
        $data = [
            'ai'    => md5($idcard),
            'name'  => $idcard_name,
            'idNum' => $idcard,
        ];

        $body    = $this->createBody($data);
        $sign    = $this->createSign($body);
        $headers = $this->getHeaders($sign);
        $headers = $this->buildHeaders($headers);

        $url = "https://api.wlc.nppa.gov.cn/idcard/authentication/check";
        $res = YqCurl::curl($url, $body, 1, 1, 5, false, $headers);
        if ($res) {
            $ret = json_decode($res, true);
            if ($ret['errcode'] != 0) {
                yqlog("请求失败", $data, $headers, $url, $res);
                return false;
            }

            return $ret['data'];
        }

        return false;
    }

    public function query($idcard)
    {
        $data = ['ai' => md5($idcard)];

        $sign    = $this->createSign($data, false);
        $headers = $this->getHeaders($sign, false);
        $headers = $this->buildHeaders($headers);

        $url = "http://api2.wlc.nppa.gov.cn/idcard/authentication/query?ai={$ai}";
        $res = YqCurl::curl($url, false, 0, 1, 5, false, $headers);
        if ($res) {
            $ret = json_decode($res, true);
            if ($ret['errcode'] != 0) {
                yqlog("请求失败", $data, $url, $res);
                return false;
            }

            return $ret['data'];
        }

        return false;
    }

    public function report($collections)
    {
        $data = [
            'collections' => $collections,
        ];

        $body    = $this->createBody($data);
        $sign    = $this->createSign($body);
        $headers = $this->getHeaders($sign);
        $headers = $this->buildHeaders($headers);

        $url = "http://api2.wlc.nppa.gov.cn/behavior/collection/loginout";
        $res = YqCurl::curl($url, $body, 1, 1, 5, false, $headers);
        if ($res) {
            $ret = json_decode($res, true);
            if ($ret['errcode'] != 0) {
                yqlog("请求失败", $data, $url, $res);
                return false;
            }

            return $ret['data'];
        }

        return false;
    }
}
